package com.qining618.cms.ucenter.controller.app;

import com.qining618.cms.ucenter.controller.app.request.AppTokenLoginRequest;
import com.qining618.cms.ucenter.controller.app.response.AppAuthLoginResponse;
import com.qining618.cms.ucenter.domain.User;
import com.qining618.cms.ucenter.service.TokenService;
import com.qining618.cms.ucenter.service.UserService;
import com.qining618.common.annotation.Access;
import com.qining618.common.contants.Group;
import com.qining618.common.contants.HeaderConstants;
import com.qining618.common.context.ContextHandle;
import com.qining618.common.enums.CallSourceEnum;
import com.qining618.common.result.ApiResult;
import com.qining618.common.result.ErrorCode;
import com.qining618.common.utils.RequestUtil;
import com.qining618.common.utils.StringUtils;
import com.qining618.common.utils.ValidatordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Description;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * <p>
 * 登录凭证管理 前端控制器
 * </p>
 *
 * @author qining
 * @since 2019-09-16
 */
@RestController
@RequestMapping("/app/api/ucenter/token")
public class AppTokenController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private UserService userService;

    @PostMapping(value = "login")
    @Description("登录")
    public ApiResult login(
            HttpServletRequest request,
            @RequestBody AppTokenLoginRequest loginRequest) {
        CallSourceEnum callSource = CallSourceEnum.getCallSource(request.getHeader(HeaderConstants.CALL_SOURCE));
        String ip = RequestUtil.getIpAddr(request);
        User user = null;
        if (CallSourceEnum.WECHAT_MINI == callSource) {
            /// code登录
//            if (StringUtils.isBlank(loginRequest.getCode())) {
//                return ApiResult.failed(ErrorCode.PARAM_IS_BLANK, "code不能为空");
//            }
//            user = userService.getByWechatMiniCode(loginRequest.getCode(), ip);

            /// 小程序手机号登录
            ValidatordUtil.validate(loginRequest, Group.WECHAT_MINI.class);
            user = userService.getByWechatMiniPhone(loginRequest.getCode(), loginRequest.getEncryptedData(),
                    loginRequest.getIv(), ip);
        }

        if (user == null) {
            return ApiResult.failed(ErrorCode.DATA_NOT_FOUND, "用户不存在");
        }

        // 获取返回信息
        AppAuthLoginResponse loginResponse = this.getLoginResponse(user, true);

        // 更新登录成功信息
        userService.updateLoginSuccess(user.getId(), ip);

        return ApiResult.ok(loginResponse);
    }

    @Access
    @GetMapping(value = "info")
    @Description("获取当前登录用户信息")
    public ApiResult info() {
        Long userId = ContextHandle.getUserId();
        User user = userService.getById(userId);
        return ApiResult.ok(getLoginResponse(user, false));
    }


    /**
     * 获取登录返回信息
     * @param user 用户信息
     * @param needToken 是否需要token
     * @return AppAuthLoginResponse
     */
    private AppAuthLoginResponse getLoginResponse(User user, boolean needToken) {
        String accessToken = null;

        if (needToken) {
            // 生成资源访问凭证
            accessToken = tokenService.generateAccessToken(user.getId());
        }

        // 返回信息
        return AppAuthLoginResponse.builder()
                .accessToken(accessToken)
                .userId(user.getId())
                .username(user.getUsername())
                .nickname(user.getNickname())
                .avatar(user.getAvatar())
                .build();
    }
}

